/**
 * @file tiny_driver.h
 * @author 张恒宣
 * @LastEditTime 2025/5/08
 *
 * MIT License
 *
 * Copyright (c) 2025 张恒宣 luckkeymail@163.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#ifndef __TINY_DRIVER_H__
#define __TINY_DRIVER_H__

#include "tiny_def.h"
#include "tiny_list.h"

typedef struct
{
    int (*open)(tiny_uint32_t arg);
    int (*close)(tiny_uint32_t arg);
    tiny_uint32_t (*read)(void* buf, tiny_uint32_t size, tiny_uint32_t arg);
    tiny_uint32_t (*write)(void* buf, tiny_uint32_t size, tiny_uint32_t arg);
} tiny_operator_t;


typedef struct
{
    const char* name;
		tiny_uint32_t arg;
    tiny_uint32_t hash;
    const tiny_operator_t* op;
    tiny_list_node_t driver_link;
} tiny_driver_t;

#define TINY_DRIVER_ENTRY(ptr) \
    STRUCT_TRANCING_PARENT(ptr, tiny_driver_t, driver_link)

#define TINY_DRIVER_FUN_DECLARE(name, call, ...) \
static inline int tiny_driver_##name(const tiny_driver_t* driver, ##__VA_ARGS__) { \
    if (driver && driver->op->name) { \
        return driver->op->call; } return -1;}

int tiny_dev_regsiter(const char* name, const tiny_operator_t* op, tiny_uint32_t arg);
int tiny_dev_unregsiter(const char* name);
const tiny_driver_t* tiny_dev_get(const char* name);
void  ting_devs_scan(int (*callback)(const tiny_driver_t* driver));

TINY_DRIVER_FUN_DECLARE(open, open(driver->arg))
TINY_DRIVER_FUN_DECLARE(close, close(driver->arg))
TINY_DRIVER_FUN_DECLARE(read, read(buf, size, driver->arg), void* buf, tiny_uint32_t size)
TINY_DRIVER_FUN_DECLARE(write, write(buf, size, driver->arg), void* buf, tiny_uint32_t size)

#endif //!__TINY_DRIVER_H__
